package com.mr.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * Class: TokenFilter
 * User (作者):MRui
 * TODO (描述)：zuul过滤器
 * Date 2018-11-14 23:09
 */
@Component
public class TokenFilter extends ZuulFilter {
    /**返回过滤器的类型。有pre、route、post、error等几种取值，分别对应上文的几种过滤器。详细可以参考com.netflix.zuul.ZuulFilter.filterType() 中的注释。*/
    @Override
    public String filterType() {
        //前置过滤器（请求前） 可用来限流 鉴权 参数校验，请求转发等
        //POST_TYPE（请求后） 后置过滤器 可用记录统计，日志等
        return PRE_TYPE;
    }
    /**，返回一个int值来指定过滤器的执行顺序，不同的过滤器允许返回相同的数字*/
    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }
    /**是否执行*/
    @Override
    public boolean shouldFilter() {
        return false;
    }
    /** 逻辑*/
    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = requestContext.getRequest();
        //获取token
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)){
            //不通过
            requestContext.setSendZuulResponse(false);
            //设置http状态码 401权限不足
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
